import { Page } from '@/base/Page';
import { deleteNews, postNewsevocation, getNewsList, getPush } from '@/base/api/NewsApi';
import { News } from '@/base/model/News';
import { isEmpty } from '@/base/util/Strings';

class Form {
  userName = '';
  title = '';
  pushStatus = '';
  createBegin = '';
  createEnd = '';
  date = [];
  companyId = [];
}

export class ListBloc {
  form = new Form();

  paged: Page<News> = new Page<News>([], 0, 1, 15, 0, []);
  loading = false;

  load(pageIndex: number, pageSize: number) {
    if (!isEmpty(this.form.date) && !isEmpty(String(this.form.date[0]))) {
      // @ts-ignore
      this.form.createBegin = this.form.date[0].getTime() || '';
      // @ts-ignore
      this.form.createEnd = this.form.date[1].getTime() + 24 * 60 * 60 * 1000 || '';
    } else {
      this.form.createBegin = '';
      this.form.createEnd = '';
    }
    this.loading = true;
    return getNewsList({
      pageIndex,
      pageSize,
      userName: this.form.userName,
      title: this.form.title,
      pushStatus: this.form.pushStatus,
      createBegin: this.form.createBegin,
      createEnd: this.form.createEnd,
      companyId: this.form.companyId
    }).then((res) => {
      // console.log(res)
      this.paged = res.data;
    }).finally(() => {
      this.loading = false;
    });
  }

  removeItem(dateItem: News) {
    this.loading = true;
    return deleteNews(dateItem.id)
      .finally(() => {
        this.loading = false;
      });
  }

  pushItem(id: number) {
    return getPush({ id })
  }

  cancelItem(id: number) {
    this.loading = true;
    return postNewsevocation(id).finally(() => {
      this.loading = false;
    });
  }

  reset() {
    this.form = new Form();
    this.paged.pageIndex = 1;
    this.paged.pageSize = 15;
    this.load(this.paged.pageIndex, this.paged.pageSize);

  }

  getTargetType(type: string) {
    const obj = {
      'TEXT': '纯文本',
      'EXTERNAL': '外链',
      'INTERNAL': '资讯'
    };
    return obj[type] || '纯文本';
  }

  getCompanyName(companyId: number) {
    const item = this.paged.extras.find(x => x.id === companyId && x.hasOwnProperty('name'));
    return item == null ? '' : item.name;
  }

}
